<?php

namespace app\controllers\h5\uni;

use app\controllers\h5\base\H5Controller;

use app\controllers\wx\services\Template;
use app\models\SetExpressApi;
// use app\models\SetExpressApi as Model;
use app\models\ZRegion;
use app\util\Debug;
use app\util\Request;
use app\controllers\h5\uni\address\AddressTool;

class ExpressApi
{
    private $url = 'https://api.yunyangwl.com/api/wuliu/openService';

    // 这个是基础接口测试环境
    // private $url = 'https://api.yunyangwl.com/api/sandbox/openService';

    /*
     * 检测渠道
     * CHECK_CHANNEL_INTELLECT
     *
     * 下单
     * ADD_BILL_INTELLECT
     *
     * 取消
     * CANCEL
     *
     * 查询轨迹
     * QUERY_TRANCE
     *
     * 查询订单详情
     * QUERY_BILL_INFO
     *
     */

    private function signature($appid, $appkey, $request_id, $timestamp)
    {

        $str = $appid . $request_id . $timestamp . $appkey;
        $sign = md5($str);

        return $sign;
    }

    // 这个是类似java的uuid
    private function uuid()
    {
        // return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        return sprintf( '%04x%04x%04x%04x%04x%04x%04x%04x',
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
            mt_rand( 0, 0xffff ),
            mt_rand( 0, 0x0fff ) | 0x4000,
            mt_rand( 0, 0x3fff ) | 0x8000,
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
        );
    }

    // 过滤火星文
    function removeEmojiAndSpecialChars($string) {
        // 过滤掉Emoji表情
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $cleanString = preg_replace($regexEmoticons, '', $string);

        // 过滤掉其他符号和图片等
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $cleanString = preg_replace($regexSymbols, '', $cleanString);

        // 过滤掉运输和地图符号
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $cleanString = preg_replace($regexTransport, '', $cleanString);

        // 过滤掉部分Unicode符号
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $cleanString = preg_replace($regexMisc, '', $cleanString);

        // 过滤掉其他特殊符号
        $regexOthers = '/[\x{2700}-\x{27BF}]/u';
        $cleanString = preg_replace($regexOthers, '', $cleanString);

        // 过滤掉其他所有非字母非数字符号
        $cleanString = preg_replace('/[^A-Za-z0-9]/', '', $cleanString);

        return $cleanString;
    }

    // 用这个过滤 火星文
    function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }


    // 这个是真实的下单
    // 也是就是支付完成后, 再下单
    public function order($data, $order)
    {

        // var_dump($data);exit;

        $set = SetExpressApi::getLastOne();

        // java中用的是微秒
        $time = time() * 1000;

        $uuid = $this->uuid();
        $sign = $this->signature($set->appid, $set->appkey, $uuid, $time);

        // var_dump($uuid, $sign);exit;

        // $data['send']['nickname'] = "Here😂 is #a \u{1F601} sample!";
        // $data['send']['nickname'] = "严庆🔥软件开发🔥";

        // 模拟下单失败
        // $data['send']['nickname'] = "";

        // 下单失败:寄件人字符长度超限
        if (isset($data['send']['nickname']) && $data['send']['nickname']) {

            $data['send']['nickname'] = $this->filterEmoji($data['send']['nickname']);

            // var_dump($data['send']);exit;

            if (mb_strlen($data['send']['nickname']) > 10) {
                $data['send']['nickname'] = mb_substr($data['send']['nickname'], 0, 10);
            }
        }

        // var_dump($data);exit;

        // 直辖市处理
        if ($data['receive']['city']['city'] === '直辖市') {
            $data['receive']['city']['city'] = $data['receive']['city']['province'];
        }
        if ($data['send']['city']['city'] == '直辖市') {
            $data['send']['city']['city'] = $data['send']['city']['province'];
        }

        $params = [
            'serviceCode' => 'ADD_BILL_INTELLECT',
            'timeStamp' => $time,
            'requestId' => $uuid,
            'appid' => $set->appid,
            'sign' => $sign,
            'content' => [
                'channelId' => $data['channel']['channelId'] ,
                'itemName' => $data['product']['name'] ,
                'channelTag' => $data['type'] == 2 ? "重货": "智能",
                // 'channelSubTag' => '申通',
                'sender' => $data['send']['nickname'],
                'senderMobile' => $data['send']['mobile'],
                'senderProvince' => $data['send']['city']['province'],
                'senderCity' => $data['send']['city']['city'],
                'senderCounty' => $data['send']['city']['area'],
                // 'senderTown' => '',
                'senderLocation' => $data['send']['address'],
                // 'senderAddress' => '',
                'receiver' => $data['receive']['nickname'],
                'receiverMobile' => $data['receive']['mobile'],
                'receiveProvince' => $data['receive']['city']['province'],
                'receiveCity' => $data['receive']['city']['city'],
                'receiveCounty' => $data['receive']['city']['area'],
                // 'receiveTown' => '',
                'receiveLocation' => $data['receive']['address'],
                // 'receiveAddress' => '',
                'weight' => $data['product']['weight'],
                'packageCount' => 1,
                // 'insured' => 1,
                // 'vloumLong' => 1,
                // 'vloumWidth' => 1,
                // 'vloumHeight' => 1,
            ]
        ];

        // $content = $this->post('content');
        // $params['content'] = $content;

        // var_dump($data);exit;



        // var_dump($data);exit;

        // 处理一下预约时间
        if (isset($data['time']) && isset($data['time']['day']) && isset($data['time']['time'])
            && $data['time']['day'] && $data['time']['time']) {

            if ($data['time']['day'] == '明天') {
                $d = date('Y-m-d', strtotime('+1 day'));
            } else if ($data['time']['day'] == '后天') {
                $d = date('Y-m-d', strtotime('+2 day'));
            } else {
                $d = date('Y-m-d');
            }

            $t = explode('-', $data['time']['time']);
            $begin = trim($t[0]);
            $end = trim($t[1]);

            $start_time = $d . ' ' . $begin . ':00';
            $end_time = $d . ' ' . $end . ':00';

            // var_dump($start_time, $end_time);


            $params['pickupStartTime'] = $start_time;
            $params['pickupStopTime'] = $end_time;
        }

        // var_dump(22);exit;

        // 备注
        if (isset($data['remark']) && $data['remark']) {
            $params['billRemark'] = $data['remark'];
        }

        $ret = Request::json($this->url, json_encode($params));

        // var_dump($result);exit;

        $result = json_decode($ret, true);
        if ($result && $result['code'] != 1) {
            // if (isset($result['message'])) {
            //     throw new \Exception($result['message']);
            // }
            // throw new \Exception('创建物流单失败');

            // 保存下单失败信息
            Debug::debug('express-order-fail', $ret . '-参数:' . json_encode($params));

            // 下单API失败
            if (isset($result['message'])) {
                $order->express_fail_status = 1;
                $order->express_fail = $result['message'];
                $order->save();
            } else {
                $order->express_fail_status = 1;
                $order->express_fail = '[创建物流订单失败]';
                $order->save();
            }

        } else {
            // 保存返回信息
            $order->express_request = $ret;
            $order->waybill = $result['result']['waybill'];
            $order->shopbill = $result['result']['shopbill'];

            Template::expressOrder($order);

            $order->save();

            // 小程序发货推送
            // 这里是支付完, 下单完成了
            // 所以这里推送是可以的
            // 但是有加运费支付订单
            // 1) 收件了操作
            // 2) 补运费时就操作

        }

    }

}